package com.excilys.ymca.activity;

import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.excilys.ymca.R;
import com.excilys.ymca.model.Contact;
import com.excilys.ymca.service.IContactListService;
import com.excilys.ymca.service.StaticContactListFactory;
import com.excilys.ymca.view.ContactAdapter;

/**
 * Activité listant les contacts de l'annuaire.
 */
public class ContactListActivity extends Activity {

	private ListView		contactListView;
	private List<Contact>	contacts;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.contact_list);

		retrieveData();
		findViews();
		addContent();
		addListeners();
	}

	private void addContent() {
		setTitle(R.string.contact_list_activity_title);
		ContactAdapter adapter = new ContactAdapter(this, contacts);

		contactListView.setAdapter(adapter);
	}

	private void addListeners() {
		contactListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				String phoneNumber = contacts.get(position).getPhoneNumber();
				dialPhoneNumber(phoneNumber);
			}
		});
	}

	private void retrieveData() {
		// IContactListService contactListService =
		// StaticContactListFactory.getMockService();

		IContactListService contactListService = StaticContactListFactory.getRemoteFileService();

		contacts = contactListService.getContactList();
	}

	private void findViews() {
		contactListView = (ListView) findViewById(R.id.contact_list);
	}

	private void dialPhoneNumber(String phoneNumber) {
		Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
		startActivity(intent);
	}
}